/**
 * Copyright &copy; 2014-2015 <a href="http://www.zhiqone.com">zhiqone</a> All rights reserved.
 */
package com.zcm.modules.center.utils;

import java.util.List;

import com.zcm.modules.center.dao.CenterUserDao;
import com.zcm.modules.center.entity.CenterUser;
import com.zcm.modules.center.security.CenterAuthorizingRealm;
import com.zcm.modules.sys.security.SystemAuthorizingRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.zcm.common.service.BaseService;
import com.zcm.common.utils.CacheUtils;
import com.zcm.common.utils.SpringContextHolder;
import com.zcm.modules.sys.dao.RoleDao;
import com.zcm.modules.sys.entity.Menu;
import com.zcm.modules.sys.dao.MenuDao;
import com.zcm.modules.sys.entity.Role;


/**
 * 用户工具类
 * @author liangstc
 * @version 2013-12-05
 */
public class CenterUserUtils {

    private static CenterUserDao userDao = SpringContextHolder.getBean(CenterUserDao.class);
    private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
    private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
    public static final String USER_CACHE = "centeruserCache";
    public static final String USER_CACHE_ID_ = "centerid_";
    public static final String USER_CACHE_LOGIN_NAME_ = "ln";
    public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "center_oid_";

    public static final String CACHE_ROLE_LIST = "centerroleList";
    public static final String CACHE_MENU_LIST = "centermenuList";
    public static final String CACHE_AREA_LIST = "centerareaList";
    public static final String CACHE_OFFICE_LIST = "centerofficeList";
    public static final String CACHE_OFFICE_ALL_LIST = "centerofficeAllList";

    public static final String USER_WEIXIN_CACHE="weixinCache";
    public static final String CACHE_WEIXINACCOUNT_LIST = "accountList";

    //获取微信站点
/*	public static WeixinAccount getWeixinAccount()
	{
		return null;
	}
	*/


    /**
     * 获取当前登录者对象ID
     */
    public static String getUserId(){
        try{
            String userid=(String) getSession().getAttribute("userId");
            if (userid != null){
                return userid;
            }
//			subject.logout();
        }catch (UnavailableSecurityManagerException e) {

        }catch (InvalidSessionException e){

        }
        return null;
    }

    /**
     * 根据ID获取用户
     * @param id
     * @return 取不到返回null
     */
    public static CenterUser get(String id){
        CenterUser user = (CenterUser)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
        if (user ==  null){
            user = userDao.get(id);
            if (user == null){
                return null;
            }
            //user.setRoleList(roleDao.findList(new Role(user)));
            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
            CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
        }
        return user;
    }

    /**
     * 根据登录名获取用户
     * @param loginName
     * @return 取不到返回null
     */
    public static CenterUser getByLoginName(String loginName){
        CenterUser user= userDao.getUserByLoginName(loginName);
        if (user == null){
            return null;
        }
	/*	CenterUser user = (CenterUser)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			user = userDao.getByLoginName(new CenterUser(null, loginName));
			if (user == null){
				return null;
			}
			//user.setRoleList(roleDao.findList(new Role(user)));
			//CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			//CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}*/
        return user;
    }

    /**
     * 根据unionid获取用户
     * @param unionid
     * @return 取不到返回null
     */
    public static CenterUser getByUnionID(String unionid) {
        CenterUser centerUser = new CenterUser();
        centerUser.setUnionId(unionid);
        CenterUser user= userDao.getByUnionID(centerUser);
        return user;
    }


    /**
     * 查询手机号数量
     * @param mobile
     * @return
     */
    public static CenterUser getByMobile(String mobile) {
        CenterUser centerUser = userDao.getUserByMobile(mobile);
        return centerUser;
    }

    /**
     * 清除当前用户缓存
     */
    public static void clearCache(){
        removeCache(CACHE_ROLE_LIST);
        removeCache(CACHE_MENU_LIST);
        removeCache(CACHE_AREA_LIST);
        removeCache(CACHE_OFFICE_LIST);
        removeCache(CACHE_OFFICE_ALL_LIST);
        CenterUserUtils.clearCache(getUser());
    }

    /**
     * 清除指定用户缓存
     * @param user
     */
    public static void clearCache(CenterUser user){
        CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
        CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
    }

    /**
     * 获取当前用户
     * @return 取不到返回 new User()
     */
    public static CenterUser getUser(){
        SystemAuthorizingRealm.Principal principal = getPrincipal();
        if (principal!=null){
            CenterUser user = get(principal.getId());
            if (user != null){
                return user;
            }
            return new CenterUser();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new CenterUser();
    }

    /**
     * 获取当前用户角色列表
     * @return
     */
    public static List<Role> getRoleList(){
        @SuppressWarnings("unchecked")
        List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
        if (roleList == null){
            CenterUser user = getUser();
            Role role = new Role();
            role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
            roleList = roleDao.findList(role);

            putCache(CACHE_ROLE_LIST, roleList);
        }
        return roleList;
    }

    /**
     * 获取当前用户授权菜单
     * @return
     */
    public static List<Menu> getMenuList(){
        @SuppressWarnings("unchecked")
        List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
        if (menuList == null){
            CenterUser user = getUser();

            Menu m = new Menu();
            m.setUserId(user.getId());
            menuList = menuDao.findByUserId(m);
            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }





    /**
     * 获取授权主要对象
     */
    public static Subject getSubject(){
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录者对象
     */
    public static SystemAuthorizingRealm.Principal getPrincipal(){
        try{
            Subject subject = SecurityUtils.getSubject();
            SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal)subject.getPrincipal();
            if (principal != null){
                return principal;
            }
//			subject.logout();
        }catch (UnavailableSecurityManagerException e) {

        }catch (InvalidSessionException e){

        }
        return null;
    }

    public static Session getSession(){
        try{
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session == null){
                session = subject.getSession();
            }
            if (session != null){
                return session;
            }
//			subject.logout();
        }catch (InvalidSessionException e){

        }
        return null;
    }

    // ============== User Cache ==============

    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
        Object obj = getSession().getAttribute(key);
        return obj==null?defaultValue:obj;
    }

    public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
        getSession().setAttribute(key, value);
    }

    public static void removeCache(String key) {
//		getCacheMap().remove(key);
        getSession().removeAttribute(key);
    }
//
//    public static CenterUser getUserByPhoneNum(String phoneNum) {
//        List<CenterUser> user= userDao.getUserByPhoneNum(phoneNum);
//        if (user == null || user.isEmpty()){
//            return null;
//        }
//        return user.get(0);
//    }
//




//	public static Map<String, Object> getCacheMap(){
//		Principal principal = getPrincipal();
//		if(principal!=null){
//			return principal.getCacheMap();
//		}
//		return new HashMap<String, Object>();
//	}

}
